<template>
  <div class="dashboard-container">
    <div class="app-container">

      <PageTools :show-before="true">
        <template slot="before">
          <span>有{{ attenInfo.count }}条考勤审批尚未处理</span>
        </template>
        <template slot="after">
          <el-button size="small" type="danger" @click="$router.push('/import')">导入</el-button>
          <el-badge is-dot class="item">
            <el-button is-dot size="small" type="warning" @click="tipsDialogVisible=true">提醒</el-button>
          </el-badge>
          <el-button size="small" type="primary" @click="showDialog=true">设置</el-button>
          <el-button size="small" @click="$router.push('/attendances/guidang')">历史归档</el-button>
          <el-button size="small" type="primary" @click="$router.push({ path: `/report/${reportDate}` })">{{ reportDate | reportList }}月份报表</el-button>
        </template>
        <template slot="bottom">
          <div>
            <b style="color:#555555;font-size:14px">部门:</b>
            <!-- el-checkbox-group选中的是 当前用户所拥有的角色  需要绑定 当前用户拥有的角色-->
            <el-checkbox-group v-model="checkList" @change="handleCheckedCitiesChange">
              <!-- 选项 -->
              <!-- 对于多选框来说
            1. 供计算机查看和记录的叫 label
            2. 供用户查看的放在开闭标签里面 -->
              <el-checkbox
                v-for="item in deptList"
                :key="item.id"
                :label="item.name"
              >
                {{ item.name }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
          <div style="margin-top:30px">
            <b style="color:#555555;font-size:14px;margin-right:10px">考勤状态:</b>
            <el-radio v-for="item in statusList" :key="item.id" v-model="radio" :label="item.value" @change="handlerRadio">{{ item.value }}</el-radio>
          </div>
        </template>
      </PageTools>

      <!-- 表格 -->
      <el-card>
        <el-table
          :data="attendanceList"
          border
        >
          <el-table-column
            type="index"
            width="50"
            align="center"
            label="序号"
          />
          <el-table-column
            prop="username"
            width="100"
            label="姓名"
            align="center"
          />
          <el-table-column
            prop="workNumber"
            label="工号"
            align="center"
          />
          <el-table-column
            prop="departmentName"
            label="部门"
            align="center"
          />
          <el-table-column
            prop="mobile"
            label="手机"
            width="150"
            align="center"
          />
          <el-table-column
            v-for="(item,index) in attendanceRecord"
            :key="item.day"
            align="center"
            :label="item.day | formatTime"
            :formatter="formatAttendanceRecord"
          >
            <template slot-scope="{row}">
              <div style="width:100%;height:100%" @click="showStatus(row,row.attendanceRecord[index])">
                {{ formatAttendanceRecord(row.attendanceRecord[index].adtStatu ) }}
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="text-align:center;margin:20px 0">
          <el-pagination
            :current-page="pagination.page"
            :page-sizes="[4, 6, 8, 10]"
            :page-size="pagination.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <!-- 设置弹框 -->
        <el-dialog title="设置" :visible.sync="showDialog" @close="settingBtnCancel">
          <el-tabs v-model="settingActiveName">
            <el-tab-pane label="出勤设置" name="first">
              <settingChuqin @updateShowDialog="showDialog=false" />
            </el-tab-pane>
            <el-tab-pane label="请假设置" name="second">
              <settingQingjia @updateShowDialog="showDialog=false" />
            </el-tab-pane>
            <el-tab-pane label="扣款设置" name="third">
              <settingKoukuan @updateShowDialog="showDialog=false" />
            </el-tab-pane>
            <el-tab-pane label="加班设置" name="fourth">
              <settingJiaban @updateShowDialog="showDialog=false" />
            </el-tab-pane>
          </el-tabs>
        </el-dialog>

        <!-- 考勤状态弹框 -->
        <el-dialog
          :visible="statusDialog"
          width="30%"
          center
          @close="statusCancel"
        >
          <span slot="title" style="color:#fff;">{{ statusDay | formatTime }} （实际工作日考勤方案）</span>
          <p class="red">注：统计考勤时，异常状态优先正常状态</p>
          <el-row>
            <el-radio-group v-model="statusObj.adtStatu">
              <el-radio
                v-for="item in departmentsEnum.vacationtype"
                :key="item.id"
                :label="item.id"
                :value="item.name"
              >{{ item.name }}</el-radio>
            </el-radio-group>
          </el-row>
          <el-row type="flex" justify="center" style="margin: 15px 0">
            <el-button type="primary" @click="statusOk">保存更新</el-button>
            <el-button @click="statusCancel">取消</el-button>
          </el-row>
        </el-dialog>

        <!-- 提醒弹框 -->
        <!-- 提醒组件 -->
        <el-dialog
          title="提醒"
          :visible.sync="tipsDialogVisible"
          width="280px"
          center
        >
          <div class="attenInfo">
            <p>系统将通过邮件与短信的形式，对全体员工中存在旷工的考勤进行提醒，该提醒每月仅可发送 1 次。</p>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="handleSub">我知道了</el-button>
            <el-button @click="tipsDialogVisible = false">取消</el-button>
          </span>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getDepartments } from '@/api/departments'
import { getAttendances, settingAtteStatus } from '@/api/attendance'
import departmentsEnum from '@/api/constant/attendance'
import settingChuqin from './component/setting_chuqin'
import settingQingjia from './component/setting-qingjia'
import settingKoukuan from './component/setting-koukuan'
import settingJiaban from './component/setting-jiaban'

export default {
  components: {
    settingChuqin, settingQingjia, settingKoukuan, settingJiaban
  },
  filters: {
    // 过滤器，表格头时间
    formatTime(data) {
      const month = data.substr(4, 1) === '0' ? data.substr(5, 1) : data.substr(4, 2)
      const day = data.substr(6, 1) === '0' ? data.substr(7, 1) : data.substr(6, 2)
      return month + '/' + day
    },
    // 按钮日期
    reportList(data) {
      return data.substr(0, 6)
    }
  },
  data() {
    return {
      // 提醒弹框
      tipsDialogVisible: false,
      // 设置考勤状态码
      statusObj: {
        adtStatu: '1'
      },
      statusDay: '',
      departmentsEnum,
      // 考勤状态弹框
      statusDialog: false,
      settingActiveName: 'first',
      showDialog: false,
      deptList: [],
      checkList: [],
      radio: '',
      // 渲染单选框
      statusList: [],
      // 页码
      pagination: {
        page: 2,
        pagesize: 10,
        total: 0
      },
      attendanceList: [],
      saveArr: [],
      attendanceRecord: [],
      attenInfo: {
        // 获取到的月份
        month: '',
        // 需要审批数量
        count: ''
      },
      checkboxValue: [],
      checkRodiu: [],
      reportDate: ''
    }
  },
  mounted() {
    this.getDepartments()
    this.statusList = departmentsEnum.holidayType
    console.log(this.statusList)
    this.getAttendances()
    // this.formatTime()
  },
  methods: {
    // 单选框
    handlerRadio(val, list = this.saveArr) {
      if (val.length === 0) {
        console.log('我是空的')
        return
      }
      console.log('值' + typeof val, list, '我是单选')
      this.checkRodiu = val
      const obj = departmentsEnum.vacationtype.find(item => item.name === val).id
      console.log(obj)
      let newArr = []
      // 符合条件的id值
      try {
        list.forEach(item => {
          // console.log(item.attendanceRecord)
          for (let i = 0; i <= item.attendanceRecord.length; i++) {
            if (item.attendanceRecord[i].adtStatu.toString() === obj) {
              newArr.push(item.attendanceRecord[i].id)
              return
            }
          }
        })
      } catch (err) {
        newArr = []
      }
      console.log(newArr)
      // 筛选
      const newArrList = []
      console.log('保存数据', list)
      this.attendanceList = list.filter(item => {
        newArr.forEach(item1 => {
          if (item1 === item.id) {
            console.log(item)
            newArrList.push(item)
          }
        })
      })
      this.attendanceList = newArrList
      if (list === this.saveArr) {
        this.handleCheckedCitiesChange(this.checkboxValue, this.attendanceList)
      }
    },
    // 多选框
    handleCheckedCitiesChange(value, list = this.saveArr) {
      console.log(value, list, '我是多选') // 部门名字
      if (value.length === 0) {
        this.attendanceList = list
      } else {
        this.checkboxValue = value
        const newArr = []
        console.log('保存数据', list)
        this.attendanceList = list.filter(item => {
          value.forEach(item1 => {
            if (item1 === item.departmentName) {
              console.log(item)
              newArr.push(item)
            }
          })
        })
        this.attendanceList = newArr
        if (list === this.saveArr) {
          this.handlerRadio(this.checkRodiu, this.attendanceList)
        }
      }

      console.log(this.attendanceList)
    },
    handleSub() {
      this.tipsDialogVisible = false
      this.$message.success('操作成功')
    },
    // 导入
    importAtteStatus() {
      this.$router.push({ path: '/import', query: { data: 'attendance' }})
    },
    // 考勤状态弹出框
    showStatus(row, status) {
      console.log(row, status)
      this.statusDay = status.day
      this.statusObj.adtStatu = status.adtStatu.toString()
      this.statusObj.day = status.day
      this.statusObj.departmentId = row.departmentId
      this.statusObj.userId = row.id
      console.log(this.statusObj)
      this.statusDialog = true
    },
    // 考勤状态关闭弹窗
    statusCancel() {
      this.statusDialog = false
    },
    // 考勤状态确认弹窗
    async statusOk() {
      await settingAtteStatus(this.statusObj)
      this.$message.success('操作成功')
      this.statusDialog = false
      this.getAttendances()
    },
    // 设置弹出框tab栏
    // settingHandleClick(tab, event) {
    //   console.log(tab, event)
    // },
    // 设置弹出框关闭按钮
    settingBtnCancel() {
      this.showDialog = false
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pagination.pagesize = val
      this.getAttendances()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pagination.page = val
      this.getAttendances()
    },
    async getDepartments() {
      const { depts } = await getDepartments()
      this.deptList = depts
      console.log(this.deptList)
    },
    async getAttendances() {
      const { data, monthOfReport, tobeTaskCount } = await getAttendances(this.pagination)
      this.attendanceList = data.rows
      this.saveArr = data.rows
      this.reportDate = this.attendanceList[0].attendanceRecord[0].day
      console.log(this.attendanceList)
      this.pagination.total = data.total
      this.attenInfo.month = monthOfReport
      this.attenInfo.count = tobeTaskCount
      this.attendanceRecord = data.rows[0].attendanceRecord
      // console.log(data.rows[0])
      // console.log(this.attendanceRecord)
    },
    // 格式化考勤状态
    formatAttendanceRecord(cellValue) {
      const obj = departmentsEnum.vacationtype.find(item => item.id === cellValue.toString())
      return obj.name
    }

  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-row--flex.is-align-middle{
  margin-bottom: 10px;
}
::v-deep .el-table th.is-leaf{
  color: #555555;
    background-color: #fafafa;
    border-bottom: 2px solid #e8e8e8 ;
}
.item {
  margin: 0 10px;
}
.el-dialog__body{
  .el-radio {
        display: inline-block;
        width: 60px;
        padding: 5px 0;
    }
}
.red{
  margin-top: -10px;
  color: #ff0000;
}
</style>
